// pages/xq_blue/xq_receiveFile/xq_receiveFile.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceId: "",
    services: []

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log("加载")
    console.log(options)
    console.log(options.deviceId)

    var self = this
    self.setData({
      deviceId: options.deviceId
    })
  },


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log("页面结束")

    var deviceId = this.data.deviceId
    console.log(deviceId)

    wx.closeBLEConnection({
      deviceId: deviceId,
      success: function(res) {
        console.log("断开连接")
        console.log(res)
      },
    })
  },



  // 获取服务和特性
  xq_getServicesAndCharacteristics: function() {
    var self = this
    var deviceId = this.data.deviceId

    // 清除原来数据
    this.setData({
      services: []
    })

    wx.showLoading({
      title: '获取服务中',
    })

    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: function(res) {
        console.log("获取服务成功")
        console.log(res)

        // { isPrimary: true, uuid: "0000180A-0000-1000-8000-00805F9B34FB" }
        self.setData({
          services: self.data.services.concat(res.services)
        })

        for (var i = 0; i < res.services.length; i++) {
          var service = res.services[i]
          self.xq_getCharacteristics(deviceId, service.uuid)
        }

      },
    })


  },

  // 获取特性
  xq_getCharacteristics: function(deviceId, serviceId) {
    console.log(deviceId + serviceId)
    var self = this
    var servers = this.data.services

    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: serviceId,
      success: function(res) {

        // properties : { notify: false, write: false, indicate: false, read: true }
        // uuid : "00002A29-0000-1000-8000-00805F9B34FB"

        for (var i = 0; i < servers.length; i++) {
          if (servers[i].uuid == serviceId) {
            servers[i]["characteristics"] = res.characteristics

            self.setData({
              services: servers
            })

            break
          }
        }

        console.log("获取特性成功")
        console.log(res)

        wx.hideLoading()

      },
    })

  },


  // 点击特征值
  xq_tapCharacteristics: function(data) {
    var self = this
    var item = data.target.dataset.item

    wx.showActionSheet({
      itemList: ["写入数据", "发送图片", "发送视频"],
      success: function(res) {

        if (res.tapIndex == 0) {
          wx.showToast({
            title: '目前还不支持',
            icon: 'none'
          })
        } else if (res.tapIndex == 1) {
          self.xq_selectImage(item.uuid)
        } else if (res.tapIndex == 2) {
          self.xq_selectVideo(item.uuid)
        }

      }
    })

  },


  xq_selectVideo: function(characteristicsUUID) {
    var self = this
    // 这里选择的视频， 是wx压缩过得
    wx.chooseVideo({
      sourceType: ["album"],
      success: function(res) {
        /**
         * duration: 1 秒
         * height: 高
         * width: 宽
         * size: 大小
         * tempFilePath: 文件地址
         */
        console.log("获取数据成功")
        console.log(res)
        self.xq_sendData(characteristicsUUID, res.tempFilePath)
      },
    })
  },


  xq_selectImage: function(characteristicsUUID) {
    let self = this
    wx.chooseImage({
      count: 1,
      sourceType: ["album"],
      success: function(res) {
        console.log("获取数据成功")
        console.log(res)
        // tempFilePaths: 只有字符串路径
        // tempFiles: 路径 and 文件大小 {path: "wxfile://tmp_e818978347374f9f45a142bb345d0f94.jpg", size: 107950}
        // { errMsg: "chooseImage:ok", tempFilePaths: Array(1), tempFiles: Array(1) }
        self.xq_sendData(characteristicsUUID, res.tempFilePaths[0])
      },
    })
  },

  xq_sendData: function(characteristicsUUID, tempFilePath) {
    var self = this
    var serverId = this.xq_getServerId(characteristicsUUID)

    console.log("各种id", self.data.deviceId, characteristicsUUID, serverId)

    var file = wx.getFileSystemManager()
    file.readFile({
      filePath: tempFilePath,
      // encoding: "binary",
      // encoding: "base64",
      success: function(res) {

        // {errMsg: "readFile:ok", data: ArrayBuffer}
        console.log("获取文件数据成功")
        console.log(res)

        var buffer = res.data

        // 切割数据发送
        let length = 18
        var count = buffer.byteLength / length
        let totalDataView = new DataView(buffer)

        // 余数
        let remainder = count % 1
        count -= remainder

        console.log("开始切割 %d, ", buffer.byteLength, count, remainder)

        // 发送数据
        for (var i = 0; i < count; i++) {
          // var nBufArray = buffer.slice(i, length)

          let nBufferArray = new ArrayBuffer(length)
          let dataView = new DataView(nBufferArray)

          let offset = i * length
          // 设置值
          for (var j = 0; j < length; j++) {
            // 每次设置某一位的值, int8类型
            dataView.setInt8(j, totalDataView.getInt8(offset + j))
          }
          
          let index = i
          wx.writeBLECharacteristicValue({
            deviceId: self.data.deviceId,
            serviceId: serverId,
            characteristicId: characteristicsUUID,
            value: nBufferArray,
            success: function(res) {
              // { errCode: 0, errMsg: "writeBLECharacteristicValue:ok" }
              // console.log(res)

              if (index >= count - 1) {
                wx.showActionSheet({
                  itemList: ['发送结束'],
                })
              }

            },
          })

        }

        // 发出余数
        if (remainder > 0) {
          let maxLength = count * length
          let endLength = buffer.byteLength - maxLength
          let nBufferArray = new ArrayBuffer(endLength)
          let dataView = new DataView(nBufferArray)
          // 设置值
          for (var j = 0; j < endLength; j++) {
            // 每次设置某一位的值, int8类型
            dataView.setInt8(j, totalDataView.getInt8(maxLength + j))
          }

          wx.writeBLECharacteristicValue({
            deviceId: self.data.deviceId,
            serviceId: serverId,
            characteristicId: characteristicsUUID,
            value: nBufferArray,
            success: function(res) {

            },
          })
        }

        console.log("结束切割")

      }

    })
  },


  // 传入特征id, 获取serverId
  xq_getServerId: function(characteristicsUUID) {
    var serverId;
    for (var i = 0; i < this.data.services.length; i++) {
      var server = this.data.services[i]
      for (var j = 0; j < server.characteristics.length; j++) {
        var characteristic = server.characteristics[j]
        if (characteristic.uuid == characteristicsUUID) {
          serverId = server.uuid
          break;
        }
      }

    }

    return serverId
  },









  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }

})